<?php
/* Kammerath Network Website System - Administration */
require_once("../config.php");

// external libraries
require_once("../lib/Smarty/Smarty.class.php");

// application internal classes
require_once("../class/cache.class.php");
require_once("../class/database.class.php");
require_once("../class/blog.class.php");
require_once("../class/facebook.class.php");
require_once("../class/imagestock.class.php");

// set to false by default
$is_admin = false;

$b = new blog($_SERVER["HTTP_HOST"]);
$f = new facebook();
if($f->isLoggedIn()){
	// get the facebook user
	$user = $f->getUser();
	if($user!=null){
		// get the param that indicates whether the user is admin or not
		$is_admin = $b->db->userIsAdmin($user->username);
	}
	
	// build the admin ui when user is authorized
	if($is_admin){
		// define the view
		$admin_view = "article";
		if(array_key_exists("view", $_GET)){
			$admin_view = $_GET["view"];
		}
		
		// define the action
		$admin_action = "list";
		if(array_key_exists("action", $_GET)){
			$admin_action = $_GET["action"];
		}
		
		// instanciate the template engine
		$template = new Smarty();
		
		// check the view
		switch($admin_view){
			case "article":
				// load the list of all articles
				$article_list = $b->db->getArticleList();
				$category_list = $b->db->getCategoryList();
				$article_category_list = $b->db->getArticleCategoryList();
				$article_item = "";
				
				/* delete item, when requested */
				if($admin_action=="delete"){
					// deletes the item
					$b->db->deleteArticle($_GET["item"]);
					
					// refresh the article list
					$article_list = $b->db->getArticleList();
				}
				
				/* check if there is post data that includes an
				 * article that we need to store in the database */
				if($admin_action=="edit"){
					if(array_key_exists("articleBody",$_POST)){
						// default is 'not published'
						$article_published = false;
						
						// check for the published checkbox
						if(array_key_exists("articlePublished",$_POST)){
							if($_POST["articlePublished"]=="on"){
								$article_published = true;
							}
						}
						
						// default publish date tomorrow
						$article_date = time()+86400;
						
						// check if the article date has been submitted
						if(array_key_exists("articleDate",$_POST)){
							$ftime = strptime($_POST["articleDate"],"%d.%m.%Y %H:%M");
							$article_date = mktime($ftime['tm_hour'],$ftime['tm_min'],
	                    					$ftime['tm_sec'],1 ,$ftime['tm_yday'] + 1,
	                   						$ftime['tm_year'] + 1900); 
						}
						
						// get the image for the article (used to feature it)
						$articleImage = $b->getArticleImage($_POST["articleBody"]);
						
						// insert the article into the database
						$b->db->addArticle($_POST["articleTitle"], $_POST["articleUrl"],
											$_POST["articleKeyword"], $_POST["articleBody"], 
											$user->username, $article_published, $article_date,
											$articleImage);
						
						/* finally, link the categories for this article */
						for($c=0; $c<count($category_list); $c++){
							// checkboxes only send their values,
							// when they're checked
							$cat_checkbox = "articleCategory_".$category_list[$c]["url"];
							if(array_key_exists($cat_checkbox,$_POST)){
								// add the art/cat link when it exists
								$b->db->addArticleCategory($_POST["articleUrl"], 
														$category_list[$c]["url"]);
							}else{
								// remove the link when its not present
								$b->db->deleteArticleCategory($_POST["articleUrl"], 
														$category_list[$c]["url"]);
							}
						}
						
						// define the article item we added
						$article_item = $_POST["articleUrl"];
											
						// refresh the article list
						$article_list = $b->db->getArticleList();
					}
					
					// add the article item to the template
					if(array_key_exists("item",$_GET)){
						$article_item = $_GET["item"];
					}
					if(strlen($article_item)>0){
						$template->assign("item_name",$article_item);
						for($a=0;$a<count($article_list);$a++){
							if($article_list[$a]["url"]==$article_item){
								$articleItem = $b->db->getArticle($article_list[$a]["url"]);
								$template->assign("item",$articleItem);
							}
						}
					}
				}
				
				// retrieve the article and category list
				$template->assign("language_list",$b->db->getLanguageList());
				$template->assign("category_list",$category_list);
				$template->assign("article_list",$article_list);
				$template->assign("article_category_list",$article_category_list);				
				break;
			case "category":
				// retrieve the list of categories
				$categoryList = $b->db->getCategoryList();
				
				/* delete item, when requested */
				if($admin_action=="delete"){
					// deletes the item
					$b->db->deleteCategory($_GET["item"]);
					
					// reload the category list
					$categoryList = $b->db->getCategoryList();
				}
				
				if($admin_action=="edit"){
					// get the item name
					$item_name = "";
					if(array_key_exists("item", $_GET)){
						$item_name = $_GET["item"];
					}
					
					// check if there is post data that we need to save
					if(array_key_exists("articleBody",$_POST)){
						// post it into the database
						$b->db->addCategory($_POST["articleTitle"], 
							$_POST["articleUrl"], $_POST["articleBody"]);
						
						// redefine the item
						$item_name = $_POST["articleUrl"];
							
						// once this is done, we need a refresh of the list
						$categoryList = $b->db->getCategoryList();
					}
					
					// assign the item name to the template
					$template->assign("item_name",$item_name);
					
					// also assign the item itself by searching for
					// it in the list we retrieved above to minimize
					// the amount of queries to the database
					for($c=0;$c<count($categoryList);$c++){
						if($categoryList[$c]["url"]==$item_name){
							$template->assign("item",$categoryList[$c]);
						}
					}
				}
				
				// finally assign the category list
				$template->assign("category_list",$categoryList);
				
				break;
			case "image":
				// instanciate the image stock
				$stock = new imagestock();
				
				// check if a file upload is requested
				$stock->checkUpload();
				
				// check for delete requests
				if(array_key_exists("action", $_GET)==true
					&& array_key_exists("item", $_GET)){
					if($_GET["action"]=="delete"){
						$stock->deleteImage($_GET["item"]);
					}					
				}
				
				// asign the images to the list
				$template->assign("imageList",$stock->getImageList());
				break;
			case "configuration":
				// get the keys of the post vals
				$postKeys = array_keys($_POST);
				
				// iterate through all keys in the post obj
				for($k=0;$k<count($postKeys);$k++){
					if(substr($postKeys[$k], 0,8)=="setting_"){						
						// define the setting code
						$settingCode = substr($postKeys[$k], 8);	
						// ge the new value to set
						$settingValue = $_POST[$postKeys[$k]];
						
						// make sure its not an
						// empty string or just spaces
						if(strlen(trim($settingValue))>0){
							// finally store it in the database
							$b->db->setSetting($settingCode, $settingValue);
						}
					}
				}
				
				// assign the list of settings
				$template->assign("settingList",$b->db->getSettingList());
				break;
		}
		
		// show the admin UI, when the user is administrator
		$template->assign("view",$admin_view);
		$template->assign("action",$admin_action);
		$template->assign("datetime_now",date("d.m.Y H:i"));
		$template->display("../themes/admin/index.tpl");
	}
	
}

// throw 403, when the user is not admin
if(!$is_admin){
	header ("HTTP/1.1 403 Forbidden");
	echo ("<b>AUTHENTICATION REQUIRED</b> OR "
		."<b>PROVIDED CREDENTIALS INVALID.</b>");
}
?>